"""
JH子系统 - 增强匹配服务
提供多模态数据融合、时间序列分析、竞争力分析等高级功能
"""

import asyncio
import numpy as np
from typing import Dict, List, Any, Optional, Tuple
from datetime import datetime, timedelta
from dataclasses import dataclass
import json
import re
from pathlib import Path
import sqlite3
from collections import defaultdict

from .intelligent_matching import (
    IntelligentMatchingEngine, UserProfile, JobPosition, MatchResult,
    SkillAssessment, SkillLevel, MatchingMode
)

@dataclass
class MultiModalProfile:
    """多模态用户画像"""
    basic_profile: UserProfile
    resume_analysis: Dict[str, Any]
    education_deep_analysis: Dict[str, Any]
    behavioral_patterns: Dict[str, Any]
    social_media_insights: Dict[str, Any]
    code_analysis: Dict[str, Any]
    interview_performance: Dict[str, Any]

@dataclass
class MarketCompetitiveness:
    """市场竞争力分析"""
    overall_score: float
    skill_competitiveness: Dict[str, float]
    salary_competitiveness: float
    experience_competitiveness: float
    education_competitiveness: float
    market_position: str  # "top_10%", "top_25%", etc.
    improvement_areas: List[str]
    competitive_advantages: List[str]

@dataclass
class CareerTrajectoryPrediction:
    """职业发展轨迹预测"""
    predicted_positions: List[Dict[str, Any]]
    timeline: List[Dict[str, Any]]
    skill_development_path: List[Dict[str, Any]]
    salary_progression: List[Dict[str, Any]]
    risk_factors: List[str]
    success_probability: float

class TimeSeriesAnalyzer:
    """时间序列分析器"""
    
    def __init__(self):
        self.skill_trends = {}
        self.salary_trends = {}
        self.demand_trends = {}
    
    def analyze_skill_evolution(self, user_profile: UserProfile) -> Dict[str, Any]:
        """分析技能演进轨迹"""
        career_trajectory = user_profile.career_trajectory
        
        if len(career_trajectory) < 2:
            return {"evolution_rate": 0.5, "trend": "stable", "predictions": []}
        
        skill_timeline = []
        for position in career_trajectory:
            skills = position.get("skills", [])
            start_date = datetime.fromisoformat(position.get("start_date", "2020-01-01"))
            
            skill_timeline.append({
                "date": start_date,
                "skills": skills,
                "position": position.get("title", "")
            })
        
        # 分析技能增长速度
        evolution_metrics = self._calculate_skill_evolution_metrics(skill_timeline)
        
        # 预测未来技能发展
        future_predictions = self._predict_future_skills(skill_timeline)
        
        return {
            "evolution_rate": evolution_metrics["growth_rate"],
            "trend": evolution_metrics["trend"],
            "skill_acquisition_pattern": evolution_metrics["pattern"],
            "predictions": future_predictions,
            "specialization_score": evolution_metrics["specialization"],
            "diversification_score": evolution_metrics["diversification"]
        }
    
    def _calculate_skill_evolution_metrics(self, skill_timeline: List[Dict[str, Any]]) -> Dict[str, Any]:
        """计算技能演进指标"""
        if len(skill_timeline) < 2:
            return {"growth_rate": 0.5, "trend": "stable", "pattern": "steady", 
                   "specialization": 0.5, "diversification": 0.5}
        
        # 计算技能增长率
        skill_counts = [len(entry["skills"]) for entry in skill_timeline]
        growth_rates = []
        
        for i in range(1, len(skill_counts)):
            time_diff = (skill_timeline[i]["date"] - skill_timeline[i-1]["date"]).days / 365
            if time_diff > 0:
                growth_rate = (skill_counts[i] - skill_counts[i-1]) / time_diff
                growth_rates.append(growth_rate)
        
        avg_growth_rate = np.mean(growth_rates) if growth_rates else 0
        
        # 分析趋势
        if avg_growth_rate > 2:
            trend = "accelerating"
        elif avg_growth_rate > 0.5:
            trend = "growing"
        elif avg_growth_rate > -0.5:
            trend = "stable"
        else:
            trend = "declining"
        
        # 分析模式
        growth_variance = np.var(growth_rates) if growth_rates else 0
        if growth_variance < 0.5:
            pattern = "steady"
        elif growth_variance < 2:
            pattern = "variable"
        else:
            pattern = "erratic"
        
        # 计算专业化vs多样化分数
        all_skills = set()
        specialized_skills = defaultdict(int)
        
        for entry in skill_timeline:
            for skill in entry["skills"]:
                all_skills.add(skill)
                specialized_skills[skill] += 1
        
        specialization_score = max(specialized_skills.values()) / len(skill_timeline) if specialized_skills else 0
        diversification_score = len(all_skills) / (len(skill_timeline) * 5)  # 假设每个阶段平均5个技能
        
        return {
            "growth_rate": min(avg_growth_rate / 3, 1.0),  # 归一化
            "trend": trend,
            "pattern": pattern,
            "specialization": min(specialization_score, 1.0),
            "diversification": min(diversification_score, 1.0)
        }
    
    def _predict_future_skills(self, skill_timeline: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """预测未来技能发展"""
        if len(skill_timeline) < 2:
            return []
        
        # 分析技能发展模式
        recent_skills = set()
        for entry in skill_timeline[-2:]:  # 最近两个职位
            recent_skills.update(entry["skills"])
        
        # 基于技能关联性预测
        skill_relationships = {
            "Python": ["机器学习", "数据科学", "AI开发"],
            "JavaScript": ["TypeScript", "React", "Node.js"],
            "数据分析": ["机器学习", "深度学习", "大数据"],
            "项目管理": ["敏捷开发", "产品管理", "团队领导"]
        }
        
        predictions = []
        for skill in recent_skills:
            if skill in skill_relationships:
                for related_skill in skill_relationships[skill]:
                    if related_skill not in recent_skills:
                        predictions.append({
                            "skill": related_skill,
                            "probability": 0.7,
                            "timeline": "6-12个月",
                            "reasoning": f"基于{skill}技能的自然发展路径"
                        })
        
        return predictions[:5]  # 返回前5个预测
    
    def analyze_career_progression_speed(self, user_profile: UserProfile) -> Dict[str, Any]:
        """分析职业发展速度"""
        career_trajectory = user_profile.career_trajectory
        
        if len(career_trajectory) < 2:
            return {"progression_speed": "medium", "analysis": "数据不足"}
        
        # 计算职位变化频率
        position_changes = []
        for i in range(1, len(career_trajectory)):
            prev_pos = career_trajectory[i-1]
            curr_pos = career_trajectory[i]
            
            prev_end = datetime.fromisoformat(prev_pos.get("end_date", "2020-01-01"))
            curr_start = datetime.fromisoformat(curr_pos.get("start_date", "2020-01-01"))
            
            duration = (curr_start - prev_end).days / 365
            position_changes.append(duration)
        
        avg_duration = np.mean(position_changes)
        
        # 分析薪资增长
        salary_growth = self._analyze_salary_progression(career_trajectory)
        
        # 分析职级提升
        level_progression = self._analyze_level_progression(career_trajectory)
        
        # 综合评估发展速度
        if avg_duration < 1.5 and salary_growth > 0.15:
            speed = "fast"
        elif avg_duration < 2.5 and salary_growth > 0.08:
            speed = "medium"
        else:
            speed = "slow"
        
        return {
            "progression_speed": speed,
            "avg_position_duration": avg_duration,
            "salary_growth_rate": salary_growth,
            "level_progression_rate": level_progression,
            "analysis": f"平均{avg_duration:.1f}年换岗，薪资年增长{salary_growth:.1%}"
        }
    
    def _analyze_salary_progression(self, career_trajectory: List[Dict[str, Any]]) -> float:
        """分析薪资增长趋势"""
        salaries = []
        dates = []
        
        for position in career_trajectory:
            if "salary" in position and position["salary"]:
                salary = float(position["salary"])
                start_date = datetime.fromisoformat(position.get("start_date", "2020-01-01"))
                salaries.append(salary)
                dates.append(start_date)
        
        if len(salaries) < 2:
            return 0.08  # 默认增长率
        
        # 计算年化增长率
        total_years = (dates[-1] - dates[0]).days / 365
        if total_years > 0:
            growth_rate = (salaries[-1] / salaries[0]) ** (1/total_years) - 1
            return min(growth_rate, 0.5)  # 限制最大增长率
        
        return 0.08
    
    def _analyze_level_progression(self, career_trajectory: List[Dict[str, Any]]) -> float:
        """分析职级提升速度"""
        level_mapping = {
            "实习生": 1, "初级": 2, "中级": 3, "高级": 4, "专家": 5,
            "主管": 6, "经理": 7, "总监": 8, "VP": 9, "CEO": 10
        }
        
        levels = []
        for position in career_trajectory:
            title = position.get("title", "").lower()
            level = 3  # 默认中级
            
            for level_name, level_value in level_mapping.items():
                if level_name.lower() in title:
                    level = level_value
                    break
            
            levels.append(level)
        
        if len(levels) < 2:
            return 0.5
        
        level_growth = (levels[-1] - levels[0]) / (len(levels) - 1)
        return min(level_growth / 2, 1.0)  # 归一化

class MarketCompetitivenessAnalyzer:
    """市场竞争力分析器"""
    
    def __init__(self):
        self.market_data = self._load_market_benchmarks()
    
    def _load_market_benchmarks(self) -> Dict[str, Any]:
        """加载市场基准数据"""
        return {
            "salary_percentiles": {
                "Python": {"p25": 80000, "p50": 110000, "p75": 150000, "p90": 200000},
                "机器学习": {"p25": 100000, "p50": 140000, "p75": 180000, "p90": 250000},
                "项目管理": {"p25": 90000, "p50": 120000, "p75": 160000, "p90": 220000}
            },
            "experience_benchmarks": {
                "junior": {"min_years": 0, "max_years": 2},
                "mid": {"min_years": 2, "max_years": 5},
                "senior": {"min_years": 5, "max_years": 10},
                "expert": {"min_years": 10, "max_years": 20}
            },
            "education_rankings": {
                "清华大学": 95, "北京大学": 95, "浙江大学": 90,
                "上海交通大学": 90, "复旦大学": 88, "中科院": 92
            }
        }
    
    def analyze_competitiveness(self, user_profile: UserProfile) -> MarketCompetitiveness:
        """分析用户市场竞争力"""
        # 技能竞争力分析
        skill_competitiveness = self._analyze_skill_competitiveness(user_profile)
        
        # 薪资竞争力分析
        salary_competitiveness = self._analyze_salary_competitiveness(user_profile)
        
        # 经验竞争力分析
        experience_competitiveness = self._analyze_experience_competitiveness(user_profile)
        
        # 教育背景竞争力分析
        education_competitiveness = self._analyze_education_competitiveness(user_profile)
        
        # 综合竞争力评分
        overall_score = (
            np.mean(list(skill_competitiveness.values())) * 0.4 +
            salary_competitiveness * 0.25 +
            experience_competitiveness * 0.25 +
            education_competitiveness * 0.1
        )
        
        # 确定市场地位
        market_position = self._determine_market_position(overall_score)
        
        # 识别改进领域和竞争优势
        improvement_areas = self._identify_improvement_areas(
            skill_competitiveness, salary_competitiveness,
            experience_competitiveness, education_competitiveness
        )
        
        competitive_advantages = self._identify_competitive_advantages(
            skill_competitiveness, salary_competitiveness,
            experience_competitiveness, education_competitiveness
        )
        
        return MarketCompetitiveness(
            overall_score=overall_score,
            skill_competitiveness=skill_competitiveness,
            salary_competitiveness=salary_competitiveness,
            experience_competitiveness=experience_competitiveness,
            education_competitiveness=education_competitiveness,
            market_position=market_position,
            improvement_areas=improvement_areas,
            competitive_advantages=competitive_advantages
        )
    
    def _analyze_skill_competitiveness(self, user_profile: UserProfile) -> Dict[str, float]:
        """分析技能竞争力"""
        skill_scores = {}
        
        for skill_assessment in user_profile.skills:
            skill_name = skill_assessment.skill_name
            proficiency = skill_assessment.proficiency_level.value
            confidence = skill_assessment.confidence_score
            market_demand = skill_assessment.market_demand
            
            # 基础技能分数
            proficiency_score = {
                "初级": 0.4, "中级": 0.6, "高级": 0.8, "专家": 1.0
            }.get(proficiency, 0.6)
            
            # 市场需求加权
            demand_bonus = market_demand * 0.2
            
            # 置信度调整
            confidence_factor = confidence * 0.1
            
            # 综合评分
            total_score = min(proficiency_score + demand_bonus + confidence_factor, 1.0)
            skill_scores[skill_name] = total_score
        
        return skill_scores
    
    def _analyze_salary_competitiveness(self, user_profile: UserProfile) -> float:
        """分析薪资竞争力"""
        current_salary = 0
        
        # 从最近的工作经历获取薪资信息
        if user_profile.career_trajectory:
            latest_position = user_profile.career_trajectory[-1]
            current_salary = float(latest_position.get("salary", 0))
        
        if current_salary == 0:
            return 0.5  # 无薪资信息，返回中位数
        
        # 基于技能获取市场薪资基准
        relevant_skills = [skill.skill_name for skill in user_profile.skills[:3]]
        market_salaries = []
        
        for skill in relevant_skills:
            if skill in self.market_data["salary_percentiles"]:
                salary_data = self.market_data["salary_percentiles"][skill]
                market_salaries.append(salary_data["p50"])
        
        if not market_salaries:
            return 0.5
        
        market_median = np.mean(market_salaries)
        
        # 计算薪资百分位
        if current_salary >= market_median * 1.5:
            return 0.9  # 90th percentile
        elif current_salary >= market_median * 1.2:
            return 0.75  # 75th percentile
        elif current_salary >= market_median:
            return 0.6  # 50th percentile
        elif current_salary >= market_median * 0.8:
            return 0.4  # 25th percentile
        else:
            return 0.2  # below 25th percentile
    
    def _analyze_experience_competitiveness(self, user_profile: UserProfile) -> float:
        """分析经验竞争力"""
        total_experience = 0
        
        for experience in user_profile.experience:
            duration = experience.get("duration_years", 0)
            total_experience += duration
        
        # 基于经验年限确定竞争力
        if total_experience >= 10:
            return 0.9  # 专家级别
        elif total_experience >= 5:
            return 0.8  # 高级级别
        elif total_experience >= 2:
            return 0.6  # 中级级别
        elif total_experience >= 1:
            return 0.4  # 初级级别
        else:
            return 0.2  # 新人级别
    
    def _analyze_education_competitiveness(self, user_profile: UserProfile) -> float:
        """分析教育背景竞争力"""
        education = user_profile.education
        
        university = education.get("university", "")
        degree_level = education.get("degree_level", "")
        major = education.get("major", "")
        
        # 基础学历分数
        degree_scores = {
            "博士": 1.0, "硕士": 0.8, "学士": 0.6, "专科": 0.4
        }
        base_score = degree_scores.get(degree_level, 0.5)
        
        # 学校排名加分
        school_ranking = self.market_data["education_rankings"].get(university, 70)
        school_bonus = (school_ranking - 70) / 30 * 0.2  # 最多加0.2分
        
        # 专业相关性加分（简化处理）
        relevant_majors = ["计算机", "软件", "数据", "人工智能", "机器学习"]
        major_bonus = 0.1 if any(keyword in major for keyword in relevant_majors) else 0
        
        return min(base_score + school_bonus + major_bonus, 1.0)
    
    def _determine_market_position(self, overall_score: float) -> str:
        """确定市场地位"""
        if overall_score >= 0.9:
            return "top_5%"
        elif overall_score >= 0.8:
            return "top_10%"
        elif overall_score >= 0.7:
            return "top_25%"
        elif overall_score >= 0.5:
            return "average"
        else:
            return "below_average"
    
    def _identify_improvement_areas(self, skill_comp: Dict[str, float],
                                  salary_comp: float, exp_comp: float, edu_comp: float) -> List[str]:
        """识别改进领域"""
        areas = []
        
        if salary_comp < 0.5:
            areas.append("薪资谈判和职业发展")
        
        if exp_comp < 0.6:
            areas.append("工作经验积累")
        
        if edu_comp < 0.7:
            areas.append("学历提升或专业认证")
        
        # 技能改进
        low_skills = [skill for skill, score in skill_comp.items() if score < 0.6]
        if low_skills:
            areas.append(f"技能提升：{', '.join(low_skills[:3])}")
        
        return areas
    
    def _identify_competitive_advantages(self, skill_comp: Dict[str, float],
                                       salary_comp: float, exp_comp: float, edu_comp: float) -> List[str]:
        """识别竞争优势"""
        advantages = []
        
        if salary_comp > 0.8:
            advantages.append("薪资水平领先同行")
        
        if exp_comp > 0.8:
            advantages.append("丰富的工作经验")
        
        if edu_comp > 0.8:
            advantages.append("优秀的教育背景")
        
        # 强势技能
        strong_skills = [skill for skill, score in skill_comp.items() if score > 0.8]
        if strong_skills:
            advantages.append(f"技能优势：{', '.join(strong_skills[:3])}")
        
        return advantages

class CareerTrajectoryPredictor:
    """职业发展轨迹预测器"""
    
    def __init__(self):
        self.career_patterns = self._load_career_patterns()
        self.industry_trends = self._load_industry_trends()
    
    def _load_career_patterns(self) -> Dict[str, Any]:
        """加载职业发展模式"""
        return {
            "技术路线": {
                "初级开发": {"next_roles": ["中级开发", "全栈开发"], "timeline": "1-2年"},
                "中级开发": {"next_roles": ["高级开发", "技术专家"], "timeline": "2-3年"},
                "高级开发": {"next_roles": ["技术总监", "架构师"], "timeline": "3-5年"}
            },
            "管理路线": {
                "技术专家": {"next_roles": ["技术经理", "产品经理"], "timeline": "2-3年"},
                "技术经理": {"next_roles": ["技术总监", "CTO"], "timeline": "3-5年"}
            }
        }
    
    def _load_industry_trends(self) -> Dict[str, Any]:
        """加载行业趋势"""
        return {
            "人工智能": {"growth_rate": 0.25, "outlook": "excellent"},
            "云计算": {"growth_rate": 0.20, "outlook": "very_good"},
            "数据科学": {"growth_rate": 0.18, "outlook": "good"},
            "网络安全": {"growth_rate": 0.22, "outlook": "excellent"}
        }
    
    def predict_career_trajectory(self, user_profile: UserProfile) -> CareerTrajectoryPrediction:
        """预测职业发展轨迹"""
        current_position = self._get_current_position(user_profile)
        
        # 预测可能的下一步职位
        predicted_positions = self._predict_next_positions(user_profile, current_position)
        
        # 生成时间线
        timeline = self._generate_timeline(predicted_positions)
        
        # 预测技能发展路径
        skill_development_path = self._predict_skill_development(user_profile)
        
        # 预测薪资发展
        salary_progression = self._predict_salary_progression(user_profile, predicted_positions)
        
        # 识别风险因素
        risk_factors = self._identify_risk_factors(user_profile)
        
        # 计算成功概率
        success_probability = self._calculate_success_probability(user_profile, predicted_positions)
        
        return CareerTrajectoryPrediction(
            predicted_positions=predicted_positions,
            timeline=timeline,
            skill_development_path=skill_development_path,
            salary_progression=salary_progression,
            risk_factors=risk_factors,
            success_probability=success_probability
        )
    
    def _get_current_position(self, user_profile: UserProfile) -> Dict[str, Any]:
        """获取当前职位信息"""
        if user_profile.career_trajectory:
            return user_profile.career_trajectory[-1]
        return {"title": "开发者", "level": "中级", "industry": "技术"}
    
    def _predict_next_positions(self, user_profile: UserProfile, current_pos: Dict[str, Any]) -> List[Dict[str, Any]]:
        """预测下一步可能的职位"""
        current_title = current_pos.get("title", "").lower()
        positions = []
        
        # 基于当前职位和技能预测
        if "初级" in current_title or "junior" in current_title:
            positions.extend([
                {"title": "中级软件工程师", "probability": 0.8, "timeline": "1-2年"},
                {"title": "全栈开发工程师", "probability": 0.6, "timeline": "2-3年"}
            ])
        elif "中级" in current_title or "senior" not in current_title:
            positions.extend([
                {"title": "高级软件工程师", "probability": 0.7, "timeline": "2-3年"},
                {"title": "技术负责人", "probability": 0.5, "timeline": "3-4年"},
                {"title": "产品经理", "probability": 0.4, "timeline": "2-3年"}
            ])
        else:
            positions.extend([
                {"title": "技术总监", "probability": 0.6, "timeline": "3-5年"},
                {"title": "架构师", "probability": 0.7, "timeline": "2-4年"},
                {"title": "创业/独立顾问", "probability": 0.3, "timeline": "1-3年"}
            ])
        
        # 基于技能调整概率
        user_skills = [skill.skill_name.lower() for skill in user_profile.skills]
        
        for position in positions:
            if "管理" in position["title"] or "总监" in position["title"]:
                # 检查管理技能
                management_skills = ["项目管理", "团队管理", "领导力"]
                if any(skill in user_skills for skill in management_skills):
                    position["probability"] *= 1.2
                else:
                    position["probability"] *= 0.8
            
            if "架构" in position["title"]:
                # 检查架构技能
                arch_skills = ["系统设计", "微服务", "云架构"]
                if any(skill in user_skills for skill in arch_skills):
                    position["probability"] *= 1.3
        
        return sorted(positions, key=lambda x: x["probability"], reverse=True)[:5]
    
    def _generate_timeline(self, predicted_positions: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """生成职业发展时间线"""
        timeline = []
        current_date = datetime.now()
        
        for i, position in enumerate(predicted_positions[:3]):
            timeline_parts = position["timeline"].split("-")
            min_years = int(timeline_parts[0])
            max_years = int(timeline_parts[1].replace("年", ""))
            
            avg_years = (min_years + max_years) / 2
            target_date = current_date + timedelta(days=avg_years * 365)
            
            timeline.append({
                "date": target_date.strftime("%Y-%m"),
                "position": position["title"],
                "probability": position["probability"],
                "milestone": f"预计{min_years}-{max_years}年内达成"
            })
        
        return timeline
    
    def _predict_skill_development(self, user_profile: UserProfile) -> List[Dict[str, Any]]:
        """预测技能发展路径"""
        current_skills = [skill.skill_name for skill in user_profile.skills]
        
        # 技能发展路径映射
        skill_paths = {
            "Python": ["数据科学", "机器学习", "深度学习"],
            "JavaScript": ["TypeScript", "React", "Node.js", "微服务"],
            "数据分析": ["机器学习", "深度学习", "大数据"],
            "项目管理": ["敏捷开发", "产品管理", "团队领导"]
        }
        
        development_path = []
        
        for skill in current_skills:
            if skill in skill_paths:
                for next_skill in skill_paths[skill]:
                    if next_skill not in current_skills:
                        development_path.append({
                            "skill": next_skill,
                            "prerequisite": skill,
                            "priority": "high" if next_skill in ["机器学习", "微服务"] else "medium",
                            "timeline": "6-12个月",
                            "learning_resources": ["在线课程", "项目实践", "认证考试"]
                        })
        
        return development_path[:8]  # 返回前8个技能发展建议
    
    def _predict_salary_progression(self, user_profile: UserProfile, 
                                  predicted_positions: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """预测薪资发展"""
        current_salary = 100000  # 默认薪资
        
        if user_profile.career_trajectory:
            latest_pos = user_profile.career_trajectory[-1]
            current_salary = float(latest_pos.get("salary", current_salary))
        
        progression = []
        annual_growth = 0.08  # 8%年增长率
        
        for i, position in enumerate(predicted_positions[:3]):
            years_ahead = i + 2  # 2, 3, 4年后
            
            # 基于职位调整增长率
            if "总监" in position["title"] or "架构师" in position["title"]:
                position_multiplier = 1.4
            elif "高级" in position["title"] or "负责人" in position["title"]:
                position_multiplier = 1.2
            else:
                position_multiplier = 1.1
            
            projected_salary = current_salary * (1 + annual_growth) ** years_ahead * position_multiplier
            
            progression.append({
                "year": datetime.now().year + years_ahead,
                "position": position["title"],
                "salary_range": {
                    "min": int(projected_salary * 0.9),
                    "max": int(projected_salary * 1.2),
                    "median": int(projected_salary)
                },
                "growth_rate": f"{((projected_salary / current_salary) ** (1/years_ahead) - 1) * 100:.1f}%"
            })
        
        return progression
    
    def _identify_risk_factors(self, user_profile: UserProfile) -> List[str]:
        """识别职业发展风险因素"""
        risks = []
        
        # 技能风险
        skills = [skill.skill_name for skill in user_profile.skills]
        if len(skills) < 5:
            risks.append("技能覆盖面相对较窄，建议扩展技能组合")
        
        # 经验风险
        total_experience = sum(exp.get("duration_years", 0) for exp in user_profile.experience)
        if total_experience < 3:
            risks.append("工作经验相对较少，需要积累更多实践经验")
        
        # 行业风险
        current_industry = "技术"  # 简化处理
        industry_outlook = self.industry_trends.get(current_industry, {}).get("outlook", "good")
        if industry_outlook == "poor":
            risks.append(f"{current_industry}行业发展前景存在不确定性")
        
        # 技能老化风险
        outdated_skills = ["PHP", "jQuery", "Flash"]  # 示例过时技能
        if any(skill in skills for skill in outdated_skills):
            risks.append("部分技能可能面临淘汰风险，建议更新技术栈")
        
        return risks
    
    def _calculate_success_probability(self, user_profile: UserProfile, 
                                     predicted_positions: List[Dict[str, Any]]) -> float:
        """计算成功概率"""
        factors = []
        
        # 技能匹配度
        skill_count = len(user_profile.skills)
        skill_factor = min(skill_count / 10, 1.0)  # 10个技能为满分
        factors.append(skill_factor * 0.3)
        
        # 经验因素
        total_exp = sum(exp.get("duration_years", 0) for exp in user_profile.experience)
        exp_factor = min(total_exp / 8, 1.0)  # 8年经验为满分
        factors.append(exp_factor * 0.3)
        
        # 学习能力
        learning_factor = user_profile.soft_skills.get("学习能力", 0.7)
        factors.append(learning_factor * 0.2)
        
        # 市场需求
        high_demand_skills = ["Python", "机器学习", "云计算", "数据科学"]
        user_skills = [skill.skill_name for skill in user_profile.skills]
        demand_match = len([s for s in user_skills if s in high_demand_skills]) / len(high_demand_skills)
        factors.append(demand_match * 0.2)
        
        return sum(factors)

class EnhancedMatchingService:
    """增强匹配服务主类"""
    
    def __init__(self):
        self.matching_engine = IntelligentMatchingEngine()
        self.time_analyzer = TimeSeriesAnalyzer()
        self.competitiveness_analyzer = MarketCompetitivenessAnalyzer()
        self.trajectory_predictor = CareerTrajectoryPredictor()
    
    async def comprehensive_analysis(self, user_profile: UserProfile) -> Dict[str, Any]:
        """综合分析用户画像"""
        
        # 时间序列分析
        skill_evolution = self.time_analyzer.analyze_skill_evolution(user_profile)
        career_progression = self.time_analyzer.analyze_career_progression_speed(user_profile)
        
        # 市场竞争力分析
        competitiveness = self.competitiveness_analyzer.analyze_competitiveness(user_profile)
        
        # 职业轨迹预测
        trajectory_prediction = self.trajectory_predictor.predict_career_trajectory(user_profile)
        
        return {
            "skill_evolution_analysis": skill_evolution,
            "career_progression_analysis": career_progression,
            "market_competitiveness": asdict(competitiveness),
            "career_trajectory_prediction": asdict(trajectory_prediction),
            "comprehensive_score": self._calculate_comprehensive_score(
                competitiveness, skill_evolution, career_progression
            ),
            "strategic_recommendations": self._generate_strategic_recommendations(
                competitiveness, trajectory_prediction, skill_evolution
            )
        }
    
    def _calculate_comprehensive_score(self, competitiveness: MarketCompetitiveness,
                                     skill_evolution: Dict[str, Any],
                                     career_progression: Dict[str, Any]) -> Dict[str, float]:
        """计算综合评分"""
        return {
            "market_position_score": competitiveness.overall_score,
            "growth_potential_score": skill_evolution["evolution_rate"],
            "career_momentum_score": self._normalize_progression_speed(
                career_progression["progression_speed"]
            ),
            "overall_rating": (
                competitiveness.overall_score * 0.4 +
                skill_evolution["evolution_rate"] * 0.3 +
                self._normalize_progression_speed(career_progression["progression_speed"]) * 0.3
            )
        }
    
    def _normalize_progression_speed(self, speed: str) -> float:
        """标准化职业发展速度"""
        speed_mapping = {"fast": 0.9, "medium": 0.7, "slow": 0.4}
        return speed_mapping.get(speed, 0.6)
    
    def _generate_strategic_recommendations(self, competitiveness: MarketCompetitiveness,
                                          trajectory: CareerTrajectoryPrediction,
                                          skill_evolution: Dict[str, Any]) -> List[str]:
        """生成战略建议"""
        recommendations = []
        
        # 基于市场地位的建议
        if competitiveness.market_position in ["below_average", "average"]:
            recommendations.append("建议重点提升核心竞争力，关注市场热门技能")
        
        # 基于技能发展的建议
        if skill_evolution["evolution_rate"] < 0.6:
            recommendations.append("建议加快技能学习和更新速度，保持技术敏感度")
        
        # 基于职业预测的建议
        if trajectory.success_probability > 0.8:
            recommendations.append("职业发展前景良好，建议制定清晰的长期规划")
        elif trajectory.success_probability < 0.6:
            recommendations.append("建议评估当前发展路径，考虑调整职业方向")
        
        # 基于改进领域的建议
        for area in competitiveness.improvement_areas:
            recommendations.append(f"重点改进：{area}")
        
        return recommendations

# 创建全局实例
enhanced_matching_service = EnhancedMatchingService() 